package com.share.gateway.handler;

import org.springframework.cloud.gateway.support.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import com.share.common.core.utils.ServletUtils;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 *
 * @author share
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
    {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted())
        {
            return Mono.error(ex);
        }

        String msg;

        if (ex instanceof NotFoundException)
        {
            msg = "服务未找到";
        }
        else if (ex instanceof ResponseStatusException)
        {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        }
        else
        {
            msg = "内部服务器错误";
        }

        // 改进日志记录，避免直接使用 ex.getMessage()
        logExceptionDetails(exchange, ex);

        return ServletUtils.webFluxResponseWriter(response, msg);
    }

    private void logExceptionDetails(ServerWebExchange exchange, Throwable ex)
    {
        try
        {
            String requestPath = exchange.getRequest().getPath().toString();
            String exceptionMessage = extractExceptionMessage(ex);

            log.error("[网关异常处理]请求路径:{},异常信息:{}", requestPath, exceptionMessage);
        }
        catch (Exception e)
        {
            // 防御性编程，确保日志记录本身不会出错
            log.error("[网关异常处理]日志记录失败，请求路径:{}",
                    exchange.getRequest().getPath(), e);
        }
    }

    private String extractExceptionMessage(Throwable ex)
    {
        try
        {
            // 尝试获取根本原因的消息
            Throwable rootCause = getRootCause(ex);
            return rootCause != null ? rootCause.getMessage() : ex.toString();
        }
        catch (Exception e)
        {
            // 如果获取消息失败，使用简单的类名
            return ex.getClass().getName();
        }
    }

    private Throwable getRootCause(Throwable ex)
    {
        Throwable cause;
        Throwable result = ex;

        while (null != (cause = result.getCause()) && (result != cause))
        {
            result = cause;
        }
        return result;
    }
}